package sy.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sy.model.Tad;
import sy.model.Tapk;
import sy.pageModel.ApkVersion;
import sy.service.AdServiceI;
import sy.service.ApkServiceI;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.UUID;

@Controller
@RequestMapping("/uploadController")
public class UploadController extends BaseController  {

	@Autowired
	private AdServiceI adService;

    @Autowired
    private ApkServiceI apkService;

	@RequestMapping("/uploadad")
	//@ResponseBody
	  public String uploadad(@RequestParam MultipartFile[] files,HttpServletRequest request) throws Exception{
		ServletContext context=request.getSession().getServletContext();
		String realpath = context.getRealPath("/upload");
		File filelocal = new File(realpath);
		if(!filelocal.exists()) filelocal.mkdirs();
		String hz=null;
		String localfilename=null;
		
		Tad tad=new Tad();
		
		for(MultipartFile multipartFile:files){
			
			if(!"".equals(multipartFile.getOriginalFilename())&&multipartFile.getOriginalFilename()!=null){
				hz=multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")+1);
			}
			localfilename=UUID.randomUUID().toString()+"."+hz;
			//
			if(multipartFile.getOriginalFilename().lastIndexOf("html")>0||multipartFile.getOriginalFilename().lastIndexOf("jsp")>0){
				tad.setLinkAddress("/upload/"+localfilename);
			}else{
				tad.setImagePath("/upload/"+localfilename);
			}
			SaveFileFromInputStream(multipartFile.getInputStream(),filelocal.getAbsolutePath(),localfilename);//保
			
		}
		
		adService.add(tad);
		
		return "/admanager/admanager";
	  }
	
	@RequestMapping("/upload")
	//@ResponseBody
	  public String upload(@RequestParam("filetype") String filetype,@RequestParam MultipartFile file,HttpServletRequest request) throws Exception{
		ServletContext context=request.getSession().getServletContext();
		String realpath = context.getRealPath("/upload");
		File filelocal = new File(realpath);
		if(!filelocal.exists()) filelocal.mkdirs();
		String filename="error";
		String hz=null;
		String uploadImageFileName=file.getOriginalFilename();
		
		
		if(!"".equals(uploadImageFileName)&&uploadImageFileName!=null){
			hz=uploadImageFileName.substring(uploadImageFileName.lastIndexOf(".")+1);
		}
		
		if(filetype.equals("1")){//android
			filename="Android."+hz;
		}else{//ios
			filename="IOS."+hz;
		}
		SaveFileFromInputStream(file.getInputStream(),filelocal.getAbsolutePath(),filename);//保
		//FileUtils.copyFile(file, new File(filelocal, filename));
        //获得已经发布的最新版本
        Tapk tapklastnew=apkService.getLastTapk();

        Tapk tapk=new Tapk();

        //上传app保存 版本号默认自动增加
        if(tapklastnew!=null){
            tapk.setVersion( tapklastnew.getVersion()+1);
        }else{
            tapk.setVersion("1");
        }
        tapk.setFilepath("/upload"+"/"+filename);
        tapk.setFilename(filename);
        tapk.setCreatetiem(new Date().getTime()+"");
        tapk.setBugcontent(request.getParameter("bugcontent"));
        apkService.add(tapk);

		return "/admin/uploadfile";
	  }

    //获取最新版本  < =1不用升级
    @ResponseBody
    @RequestMapping("/getLastVersion")
    public String getLastVersion(){
        JSONObject jsobj = new JSONObject();

        //获得已经发布的最新版本
        try{
            Tapk tapklastnew=apkService.getLastTapk();
            ApkVersion apkVersion=new ApkVersion();
            apkVersion.setVer(tapklastnew.getVersion()+"");
            apkVersion.setPath(tapklastnew.getFilepath());
            apkVersion.setBugcontent(tapklastnew.getBugcontent());
            jsobj.put("status", 1);
            jsobj.put("msg", apkVersion);
        }catch (Exception e){
            jsobj.put("status", -1);
            jsobj.put("msg", "内部错误");
        }

        return jsobj.toJSONString();

    }

	public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException
	   {      
	       FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);
	   
	       byte[] buffer =new byte[1024*1024];
	       int bytesum = 0;
	       int byteread = 0; 
	       while ((byteread=stream.read(buffer))!=-1)
	       {
	          bytesum+=byteread;
	          fs.write(buffer,0,byteread);
	          fs.flush();
	       } 
	       fs.close();
	       stream.close();      
	   }       

	//删除文件
	@ResponseBody
	@RequestMapping("/deleteapp")
	public void deleteapp(@RequestParam("appname") String  appname,HttpServletRequest request,HttpServletResponse response){
		PrintWriter out=null;
		JSONObject jsonObject=new JSONObject();
		try {
				out = (PrintWriter)response.getWriter();
				
				ServletContext context=request.getSession().getServletContext();
				String realpath = context.getRealPath("/upload");
				File file = new File(realpath);
				File[] files=file.listFiles();
				
				for(File f:files){
					if(f.getName().indexOf(appname)>-1){
						//删除文件
						f.delete();
						jsonObject.put("msg", true);
						break;
					}
				}
			} catch (IOException e) {
				jsonObject.put("msg", false);
				e.printStackTrace();
			}
			out.print(jsonObject);
			out.flush();
			out.close();
	}
	
	 //获取已经上传的app文件列表
	@ResponseBody
	@RequestMapping("/applist")
	public  void applist(HttpServletRequest request,HttpServletResponse response){
		ServletContext context=request.getSession().getServletContext();
		String realpath = context.getRealPath("/upload");
		File file = new File(realpath);
		File[] appfiles=file.listFiles();
		
		JSONArray array=new JSONArray();
		JSONObject jsonObject=null;
		String path = request.getContextPath();
		String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

		if(appfiles!=null){
			for(int i=0;i<appfiles.length;i++){
				jsonObject=new JSONObject();
				jsonObject.put("filename", appfiles[i].getName());
				jsonObject.put("filepath", basePath+"upload/"+appfiles[i].getName());

				array.add(jsonObject);
			}
		}
		
		PrintWriter out;
		try {
			out = (PrintWriter)response.getWriter();
				out.print(array);
				out.flush();
			out.close();
				
			} catch (IOException e) {
			e.printStackTrace();
			}
		
		
	}


}
